<script setup>
import {useRouter} from "vue-router";
import {WRITE_LIU_YAN_ROUTE} from "@/router/routes/liu/WriteLiuYan.js";
import {onBeforeMount, ref, provide} from "vue";
import {getLiuPageAPI} from "@/api/liu.js";
import useAccountStore from "@/store/modules/AccountStore.js";
import LiuItem from "@/views/liu/components/LiuItem.vue";

const router = useRouter()

// *******
// * 返回 *
// *******
const goBack = () => {
  router.back()
}

const goWriteLiuYan = () => {
  router.push({name: WRITE_LIU_YAN_ROUTE})
}

let next = 1
const pageSize = 10
const data = ref([]);
const loading = ref(false);
const finished = ref(false);
const error = ref(false);
const getMyLiu = async () => {
  loading.value = true
  const res = await getLiuPageAPI(next++, pageSize, useAccountStore().user.id)
  loading.value = false
  if (!res) {
    error.value = true
    return
  }
  if (res.pageCnt === res.current || res.pageCnt === 0) {
    finished.value = true
  }
  data.value.push(...(res.data))
}
onBeforeMount(async () => {
  await getMyLiu()
})
const onLoad = async () => {
  await getMyLiu()
};
const refreshing = ref(false);
const refresh = async () => {
  // 清空数据
  data.value = []
  // 重新加载数据
  next = 1
  finished.value = false
  // 异步更新数据
  await getMyLiu()
  refreshing.value = false
}
provide('refresh', refresh)
const onRefresh = async () => {
  await refresh()
};
</script>

<template>
  <div class="liu-yan">
    <van-nav-bar
        :title="'我的留言'"
        left-text="返回"
        left-arrow fixed
        @click-left="goBack"
        right-text="发表留言"
        @click-right="goWriteLiuYan"
        placeholder
    ></van-nav-bar>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
          v-model:loading="loading"
          v-model:error="error"
          :finished="finished"
          finished-text="没有更多了"
          error-text="请求失败，点击重新加载"
          @load="onLoad"
      >
        <div class="box-border" v-for="(liu, idx) in data">
          <LiuItem :liu="liu" :show-del="true"></LiuItem>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<style scoped lang="scss">

</style>